package com.roujuan.controller;

import com.alibaba.fastjson.JSONObject;
import com.roujuan.entity.*;
import com.roujuan.service.UserService;
import com.roujuan.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

@Controller
public class UserController {
    private String imageCode = "";
@Autowired
private UserService userService;

    @RequestMapping(method = RequestMethod.GET,path="/user/getImage")
    @ResponseBody
    public String getImageCode() throws IOException {
        JSONObject jsonObject = new JSONObject();
//        生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
//       返回验证码
        jsonObject.put("code",20000);
//        jsonObject.put("imageCode",code);
        imageCode = code;
//        将图片转为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(220,60,byteArrayOutputStream,code);
        String s = "data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
        jsonObject.put("base64",s);
        return JSONObject.toJSONString(jsonObject);
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public String getUserToken(User user,String imageCode){
        imageCode = imageCode.toUpperCase();
        System.out.println(imageCode);
        System.out.println(this.imageCode);
        JSONObject jsonObject = new JSONObject();
        if(!this.imageCode.equals(imageCode)){
            jsonObject.put("code",60002);
            jsonObject.put("data","验证码错误");
            return JSONObject.toJSONString(jsonObject);
        }
        try{
            User temp = userService.getUserByName(user.getUsername());
            if(temp == null){
                jsonObject.put("code",60000);
                jsonObject.put("data","用户名不存在");
                return JSONObject.toJSONString(jsonObject);
            }
            if(!temp.getPassword().equals(user.getPassword())){
                jsonObject.put("code",60001);
                jsonObject.put("data","密码错误");
                return JSONObject.toJSONString(jsonObject);
            }
            if (temp != null && temp.getPassword().equals(user.getPassword())) {
                // 获取成功，创建token
                String token = temp.getUsername()+"-token";
                Data data = new Data(token);
                jsonObject.put("code",20000);
                jsonObject.put("data",data);
                return JSONObject.toJSONString(jsonObject);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("user/info")
    @ResponseBody
    public String getUserInfoByToken(String token){
        try{
            UserInfo temp = userService.getUserInfoByToken(token);
            if(temp!=null){
                Data data = new Data(temp.getRoles().split(","),temp.getIntroduction(),temp.getAvatar(),temp.getName());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code",20000);
                jsonObject.put("data",data);
                return JSONObject.toJSONString(jsonObject);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("user/logout")
    @ResponseBody
    public String getUserTokenLogout(@RequestHeader("X-Token") String token){
//        System.out.println(token);
        try{
            UserInfo temp = userService.getUserInfoByToken(token);
            if(temp!=null){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code",20000);
                jsonObject.put("data","success");
                return JSONObject.toJSONString(jsonObject);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("user/create")
    @ResponseBody
    public String insertUser(@RequestHeader("X-Token") String token,User user,UserInfo userInfo){
        JSONObject jsonObject = new JSONObject();
        //  验证用户名与密码是否标准(等待更新java正则)
        if((user.getUsername().equals("") )|| (user.getPassword().length()<6)){
            jsonObject.put("code", 50000);
            jsonObject.put("data", "The user name or password does not comply with the specification");
            return JSONObject.toJSONString(jsonObject);
        }
        //  验证是否已有用户名
        if(userService.getUserByName(user.getUsername())!=null){
            jsonObject.put("code", 50001);
            jsonObject.put("data", "The username already exists");
            return JSONObject.toJSONString(jsonObject);
        }
        try{
            UserInfo temp = userService.getUserInfoByToken(token);
                if ((temp != null) && (temp.getRoles().equals("admin"))) {
                    if(userService.insertUser(user)==1){
                        int uid = user.getUid();
                        String token1 = user.getUsername()+"-token";
                        userInfo.setUid(uid);
                        userInfo.setUsername(user.getUsername());
                        userInfo.setPassword(user.getPassword());
                        userInfo.setToken(token1);
                        if(userService.insertUserInfo(userInfo)==1) {
                            jsonObject.put("code", 20000);
                            jsonObject.put("data", uid);
                            return JSONObject.toJSONString(jsonObject);
                        }
                    }
                }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "failed";
    }

    @RequestMapping("user/list")
    @ResponseBody
    public String getUserList(UserQuery userQuery){
        List<UserInfo> userInfoList =  userService.getUserList(userQuery);
        Integer total = userService.getUserListTotal(userQuery);
        UserListData items = new UserListData(total,userInfoList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 20000);
        jsonObject.put("data",items);
        return JSONObject.toJSONString(jsonObject);
    }

    @RequestMapping("user/delete")
    @ResponseBody
    public String deleteUser(Integer uid){
        Integer reslut =  userService.deleteUserById(uid);
        if(reslut==2){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 20000);
            jsonObject.put("data","success");
            return JSONObject.toJSONString(jsonObject);
        }
        return "failed";
    }

    @RequestMapping("user/update")
    @ResponseBody
    public String updateUser(@RequestHeader("X-Token") String token,UserInfo userInfo){
        UserInfo temp = userService.getUserInfoByToken(token);
        JSONObject jsonObject = new JSONObject();
//         不是admin无法操作用户
        if(!temp.getRoles().equals("admin")){
            jsonObject.put("msg","你无法操作任何用户");
            return JSONObject.toJSONString(jsonObject);
        }
//        root用户无法修改
        if(userInfo.getUid()<3){
            jsonObject.put("msg","你无法操作该用户");
            return JSONObject.toJSONString(jsonObject);
        }
        User user = new User();
        user.setPassword(userInfo.getPassword());
        user.setUsername(userInfo.getUsername());
        user.setUid(userInfo.getUid());
        Integer result1 = userService.editUser(user);
        Integer result2 = userService.editUserInfo(userInfo);
        if(result1==1 && result2==1){
            jsonObject.put("code",20000);
            jsonObject.put("data","success");
            return JSONObject.toJSONString(jsonObject);
        }
        return "failed";
    }
}
